package com.appleyk.service.impl;

import com.appleyk.core.common.PageResult;
import com.appleyk.core.dict.ResultCode;
import com.appleyk.core.dict.UserRoleEnum;
import com.appleyk.core.filter.SnFilter;
import com.appleyk.core.helper.SnPageHelper;
import com.appleyk.core.helper.SnFilterHelper;
import com.appleyk.core.helper.TokenHelper;
import com.appleyk.core.model.SnUser;
import com.appleyk.core.service.AbstractService;
import com.appleyk.dao.entity.SnUserEntity;
import com.appleyk.dao.mapper.IdMapper;
import com.appleyk.dao.mapper.user.SnUserMapper;
import com.appleyk.dao.utils.MapperUtil;
import com.appleyk.service.UserService;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>用户接口实现+继承，完成用户数据的增删改查以及用户令牌的验证</p>
 *
 * @author appleyk
 * @version V.1.0.0
 * @blob https://blog.csdn.net/appleyk
 * @date created on 下午 2:19 2019-4-28
 */
@Service
public class UserServiceImpl  extends AbstractService implements UserService {

    @Autowired
    private IdMapper idMapper;

    @Autowired
    private SnUserMapper userMapper;

    private static final String SERVICE_NAME = "user";

    @Override
    @Transactional(rollbackFor = {Exception.class, SQLException.class})
    public SnUser create(SnUser user) throws Exception {

        boolean nameIsExist = MapperUtil.nameIsExist(userMapper, SnUserEntity.class, user.getName());
        if (nameIsExist){
            throw new Exception("用户名重复");
        }

        user.setId(idMapper.getObjectId());
        SnUserEntity entity = SnUserEntity.createEntity(user);
        int insert = userMapper.insert(entity);
        if(insert > 0){
            return user;
        }
        throw new Exception("用户创建失败！");
    }

    @Override
    public Boolean delete(Long id) throws Exception {

        SnUserEntity userEntity = MapperUtil.objectIsExistById(userMapper, SnUserEntity.class, id, true);
        if(userEntity == null){
            throw new Exception("删除的用户不存在！");
        }

        // 验证是不是超管,如果超管的话，不让删除
        Integer role = userEntity.getRole();
        if(UserRoleEnum.SUPER_ADMIN.equals(UserRoleEnum.getEnum(role))){
            throw new Exception("无法删除超级管理员！");
        }

        int i = userMapper.delete(userEntity);
        if(i > 0){
            return true;
        }
        throw new Exception("删除用户失败！" );

    }

    @Override
    public SnUser update(SnUser user) throws Exception {

        boolean isExistById = MapperUtil.objectIsExistById(userMapper, SnUserEntity.class,"id", user.getId());
        if(!isExistById){
            throw new Exception("更新的用户不存在！");
        }
        SnUserEntity entity = SnUserEntity.createEntity(user);
        int i = userMapper.updateByPrimaryKeySelective(entity);
        if(i > 0){
            return user;
        }
        throw new Exception("更新用户失败！" );

    }

    @Override
    public PageResult<SnUser> query(SnFilter filter) {

        SnPageHelper.pageIntercept(filter);
        Example example = SnFilterHelper.buildQueryExample(filter, SnUserEntity.class);
        Page<SnUserEntity> gUserEntities = (Page<SnUserEntity>) userMapper.selectByExample(example);
        List<SnUser> users = new ArrayList<>();
        for (SnUserEntity snUserEntity : gUserEntities) {
            users.add(SnUserEntity.createModel(snUserEntity));
        }
        return SnPageHelper.buildPage(users,gUserEntities);

    }


    /**
     * 简单实现用户令牌的验证，不涉及token缓存及过期，不涉及用户是否在数据库中存在，仅能反解出来拿到uid即可
     * @param token 用户令牌
     */
    @Override
    public Boolean checkToken(String token) throws Exception{
        Long uid = TokenHelper.verifyToken(token);
        System.out.println("解析token获取uid = " + uid);
        return !(uid == null || uid == 0);
    }

    @Override
    protected String getServiceName() {
        return SERVICE_NAME;
    }
}
